"""
服务初始化器，负责初始化和管理所有服务
"""
import os
from typing import Dict, Any, Optional

from app.core.service_locator import ServiceLocator
from app.utils.logger import Logger

# 导入服务接口
from app.services.config_service import IConfigService
from app.services.websocket_service import IWebSocketService
from app.services.comment_service import ICommentService
from app.services.ai_service import IAIService
from app.services.speech_service import ISpeechService
from app.services.script_service import IScriptService
from app.services.audio_service import IAudioService

# 导入服务实现
from app.services.config_service_impl import ConfigService
from app.services.websocket_service_impl import WebSocketService
from app.services.comment_service_impl import CommentService
from app.services.ai_service_impl import AIService
from app.services.speech_service_impl import SpeechService
from app.services.script_service_impl import ScriptService
from app.services.audio_service_impl import AudioService
from app.services.service_registry import register_services
from app.services.state_init import StateInitializer


class ServiceInitializer:
    """
    服务初始化器，负责初始化和管理所有服务
    """
    
    def __init__(self):
        """
        初始化服务初始化器
        """
        # 获取服务定位器
        self.service_locator = ServiceLocator.get_instance()
        
        # 获取日志记录器
        self.logger = Logger.get_logger("service_initializer")
        
        # 服务实例
        self.config_service = None
        self.websocket_service = None
        self.comment_service = None
        self.ai_service = None
        self.speech_service = None
        self.script_service = None
        self.audio_service = None
    
    def initialize_services(self) -> bool:
        """
        初始化所有服务
        """
        try:
            self.logger.info("正在初始化服务...")
            
            # 注册服务
            register_services()
            
            # 初始化状态管理
            StateInitializer.initialize()
            
            # 初始化配置服务
            self._initialize_config_service()
            
            # 初始化WebSocket服务
            self._initialize_websocket_service()
            
            # 初始化音频服务
            self._initialize_audio_service()
            
            # 初始化AI服务
            self._initialize_ai_service()
            
            # 初始化其他服务
            self._initialize_other_services()
            
            self.logger.info("所有服务初始化完成")
            return True
            
        except Exception as e:
            self.logger.error(f"初始化服务失败: {str(e)}")
            import traceback
            self.logger.error(traceback.format_exc())
            return False
    
    def _initialize_config_service(self) -> None:
        """
        初始化配置服务
        """
        try:
            # 1. 初始化配置服务
            self.logger.info("正在初始化配置服务...")
            self.config_service = ConfigService("data/config.json")
            self.service_locator.register_service(IConfigService, self.config_service)
            
            # 加载配置
            if not self.config_service.load_config():
                self.logger.error("加载配置失败")
                return
            
            # 配置所有服务
            self._configure_services()
            
        except Exception as e:
            self.logger.error(f"初始化配置服务失败: {str(e)}")
    
    def _initialize_websocket_service(self) -> None:
        """
        初始化 WebSocket 服务
        """
        try:
            # 2. 初始化 WebSocket 服务
            self.logger.info("正在初始化 WebSocket 服务...")
            self.websocket_service = WebSocketService()
            self.service_locator.register_service(IWebSocketService, self.websocket_service)
            
            # 建立服务之间的连接
            self._connect_services()
            
        except Exception as e:
            self.logger.error(f"初始化 WebSocket 服务失败: {str(e)}")
    
    def _initialize_audio_service(self) -> None:
        """
        初始化音频服务
        """
        try:
            # 7. 初始化音频服务
            self.logger.info("正在初始化音频服务...")
            self.audio_service = AudioService()
            self.service_locator.register_service(IAudioService, self.audio_service)
            
            # 连接语音服务和音频服务
            # 当语音合成完成时，将语音文件传递给音频服务播放
            speech_service = self.service_locator.get_service(ISpeechService)
            speech_service.add_listener("speech_synthesized", lambda event: 
                self.audio_service.play(event.data.file_path))
            
        except Exception as e:
            self.logger.error(f"初始化音频服务失败: {str(e)}")
    
    def _initialize_ai_service(self) -> None:
        """
        初始化 AI 服务
        """
        try:
            # 4. 初始化 AI 服务
            self.logger.info("正在初始化 AI 服务...")
            self.ai_service = AIService()
            self.service_locator.register_service(IAIService, self.ai_service)
            
            # 连接 AI 服务和语音服务
            # 当 AI 生成回复时，将回复传递给语音服务合成语音
            self.ai_service.add_listener("reply_generated", lambda event: 
                self.service_locator.get_service(ISpeechService).synthesize(event.data["reply"]))
            
        except Exception as e:
            self.logger.error(f"初始化 AI 服务失败: {str(e)}")
    
    def _initialize_other_services(self) -> None:
        """
        初始化其他服务
        """
        try:
            # 3. 初始化评论服务
            self.logger.info("正在初始化评论服务...")
            self.comment_service = CommentService()
            self.service_locator.register_service(ICommentService, self.comment_service)
            
            # 5. 初始化语音服务
            self.logger.info("正在初始化语音服务...")
            self.speech_service = SpeechService()
            self.service_locator.register_service(ISpeechService, self.speech_service)
            
            # 6. 初始化脚本服务
            self.logger.info("正在初始化脚本服务...")
            self.script_service = ScriptService()
            self.service_locator.register_service(IScriptService, self.script_service)
            
            # 连接评论服务和 AI 服务
            # 当评论处理完成时，将评论传递给 AI 服务分析
            self.comment_service.add_listener("comment_processed", lambda event: 
                self.ai_service.analyze_comment(event.data))
            
            # 连接评论服务和脚本服务
            # 当评论处理完成时，检查是否匹配脚本规则
            self.comment_service.add_listener("comment_processed", lambda event: 
                self._handle_script_match(event.data, self.script_service, self.ai_service, self.speech_service))
            
            # 设置服务依赖关系
            # 评论服务 -> AI 服务
            if hasattr(self.comment_service, 'set_ai_service'):
                self.logger.info("设置AI服务到评论服务")
                self.comment_service.set_ai_service(self.ai_service)
            
            # AI服务 -> 语音服务
            if hasattr(self.ai_service, 'set_speech_service'):
                self.logger.info("设置语音服务到AI服务")
                self.ai_service.set_speech_service(self.speech_service)
            
        except Exception as e:
            self.logger.error(f"初始化其他服务失败: {str(e)}")
    
    def _connect_services(self) -> None:
        """
        建立服务之间的连接
        """
        try:
            # 获取服务实例
            websocket_service = self.service_locator.get_service(IWebSocketService)
            comment_service = self.service_locator.get_service(ICommentService)
            ai_service = self.service_locator.get_service(IAIService)
            speech_service = self.service_locator.get_service(ISpeechService)
            script_service = self.service_locator.get_service(IScriptService)
            audio_service = self.service_locator.get_service(IAudioService)
            
            # 设置服务依赖关系
            # 评论服务 -> AI 服务
            if hasattr(comment_service, 'set_ai_service'):
                self.logger.info("设置AI服务到评论服务")
                comment_service.set_ai_service(ai_service)
            
            # AI服务 -> 语音服务
            if hasattr(ai_service, 'set_speech_service'):
                self.logger.info("设置语音服务到AI服务")
                ai_service.set_speech_service(speech_service)
            
            # 连接 WebSocket 服务和评论服务
            # 当 WebSocket 收到消息时，将消息传递给评论服务处理
            websocket_service.add_listener("message_received", lambda event: 
                comment_service.process_message(event.data))
            
            # 连接评论服务和 AI 服务
            # 当评论处理完成时，将评论传递给 AI 服务分析
            comment_service.add_listener("comment_processed", lambda event: 
                ai_service.analyze_comment(event.data))
            
            # 连接评论服务和脚本服务
            # 当评论处理完成时，检查是否匹配脚本规则
            comment_service.add_listener("comment_processed", lambda event: 
                self._handle_script_match(event.data, script_service, ai_service, speech_service))
            
            # 连接 AI 服务和语音服务
            # 当 AI 生成回复时，将回复传递给语音服务合成语音
            ai_service.add_listener("reply_generated", lambda event: 
                speech_service.synthesize(event.data["reply"]))
            
            # 连接语音服务和音频服务
            # 当语音合成完成时，将语音文件传递给音频服务播放
            speech_service.add_listener("speech_synthesized", lambda event: 
                audio_service.play(event.data.file_path))
            
            self.logger.info("服务连接已建立")
            
        except Exception as e:
            self.logger.error(f"建立服务连接失败: {str(e)}")
    
    def _configure_services(self) -> None:
        """
        配置所有服务
        """
        try:
            # 获取所有配置
            config = self.config_service.get_all()
            
            # 配置 WebSocket 服务
            websocket_config = config.get("websocket", {})
            websocket_service = self.service_locator.get_service(IWebSocketService)
            websocket_service.configure(websocket_config)
            
            # 配置评论服务
            comment_config = config.get("comment", {})
            comment_service = self.service_locator.get_service(ICommentService)
            # 评论服务没有 configure 方法，但可以设置最大评论数
            if "max_comments" in comment_config:
                comment_service.max_comments = comment_config["max_comments"]
            
            # 配置 AI 服务
            ai_config = config.get("ai", {})
            ai_service = self.service_locator.get_service(IAIService)
            ai_service.configure(ai_config)
            
            # 配置语音服务
            speech_config = config.get("speech", {})
            speech_service = self.service_locator.get_service(ISpeechService)
            speech_service.configure(speech_config)
            
            # 配置脚本服务
            script_config = config.get("script", {})
            script_service = self.service_locator.get_service(IScriptService)
            script_service.configure(script_config)
            
            # 配置音频服务
            audio_config = config.get("audio", {})
            audio_service = self.service_locator.get_service(IAudioService)
            audio_service.configure(audio_config)
            
            self.logger.info("所有服务配置完成")
            
        except Exception as e:
            self.logger.error(f"配置服务失败: {str(e)}")
    
    def _handle_script_match(self, comment, script_service, ai_service, speech_service) -> None:
        """
        处理脚本匹配
        
        @param comment: 评论对象
        @param script_service: 脚本服务实例
        @param ai_service: AI 服务实例
        @param speech_service: 语音服务实例
        """
        try:
            # 检查评论是否匹配脚本规则
            rule = script_service.match_comment(comment.content, comment.user_name)
            if rule:
                # 如果匹配，使用规则中的回复
                self.logger.info(f"评论匹配脚本规则: {rule.pattern}")
                
                # 替换回复中的变量
                reply = rule.response.format(
                    user_name=comment.user_name,
                    content=comment.content
                )
                
                # 合成语音
                speech_service.synthesize(reply, priority=rule.priority)
                
                # 通知 AI 服务
                ai_service.notify(ai_service.create_event("reply_generated", {
                    "comment": comment,
                    "reply": reply,
                    "source": "script"
                }))
        except Exception as e:
            self.logger.error(f"处理脚本匹配失败: {str(e)}")
    
    def start_services(self) -> bool:
        """
        启动所有需要启动的服务
        
        @return: 启动是否成功
        """
        if self.config_service is None:
            self.logger.error("服务尚未初始化")
            return False
        
        try:
            # 启动语音服务
            speech_service = self.service_locator.get_service(ISpeechService)
            speech_service.start()
            
            # 启动音频服务
            audio_service = self.service_locator.get_service(IAudioService)
            audio_service.start()
            
            self.logger.info("所有服务已启动")
            return True
            
        except Exception as e:
            self.logger.error(f"启动服务失败: {str(e)}")
            return False
    
    def stop_services(self) -> bool:
        """
        停止所有服务
        
        @return: 停止是否成功
        """
        if self.config_service is None:
            self.logger.warning("服务尚未初始化")
            return True
        
        try:
            # 停止 WebSocket 服务
            websocket_service = self.service_locator.get_service(IWebSocketService)
            websocket_service.disconnect()
            
            # 停止语音服务
            speech_service = self.service_locator.get_service(ISpeechService)
            speech_service.stop()
            
            # 停止音频服务
            audio_service = self.service_locator.get_service(IAudioService)
            audio_service.stop()
            
            self.logger.info("所有服务已停止")
            return True
            
        except Exception as e:
            self.logger.error(f"停止服务失败: {str(e)}")
            return False
    
    def cleanup(self) -> None:
        """
        清理资源
        """
        try:
            # 停止所有服务
            self.stop_services()
            
            # 清除服务定位器中的所有服务
            self.service_locator.clear()
            
            self.config_service = None
            self.websocket_service = None
            self.comment_service = None
            self.ai_service = None
            self.speech_service = None
            self.script_service = None
            self.audio_service = None
            self.logger.info("资源清理完成")
            
        except Exception as e:
            self.logger.error(f"清理资源失败: {str(e)}")
    
    def shutdown_services(self) -> None:
        """
        关闭所有服务
        """
        try:
            # 确保所有配置都已保存
            if self.config_service:
                self.logger.info("关闭服务前确保所有配置已保存")
                self.config_service.ensure_saved()
            
            # 关闭 WebSocket 服务
            if self.websocket_service:
                self.logger.info("正在关闭 WebSocket 服务...")
                self.websocket_service.shutdown()
            
            # 关闭评论服务
            if self.comment_service:
                self.logger.info("正在关闭评论服务...")
                self.comment_service.shutdown()
            
            # 关闭 AI 服务
            if self.ai_service:
                self.logger.info("正在关闭 AI 服务...")
                self.ai_service.shutdown()
            
            # 关闭语音服务
            if self.speech_service:
                self.logger.info("正在关闭语音服务...")
                self.speech_service.shutdown()
            
            # 关闭脚本服务
            if self.script_service:
                self.logger.info("正在关闭脚本服务...")
                self.script_service.shutdown()
            
            # 关闭音频服务
            if self.audio_service:
                self.logger.info("正在关闭音频服务...")
                self.audio_service.shutdown()
            
            # 清理资源
            self.cleanup()
            
            self.logger.info("所有服务已关闭")
        except Exception as e:
            self.logger.error(f"关闭服务失败: {str(e)}")
            import traceback
            self.logger.error(traceback.format_exc())